import csv
import io
import chardet
from flask import Blueprint, jsonify, request
from flask_jwt_extended import jwt_required
from libs.conn import *
from libs.utils import *

lanips_bp = Blueprint('lanips', __name__)


@lanips_bp.route('/api/get_client_lanips', methods=['POST'])
@jwt_required()
def get_client_lanips():
    client_id = request.json.get('client_id')
    rows = fetchall("SELECT * FROM lanips WHERE client_id = ?", (client_id,))
    return { 'status': 'ok', 'data': rows }

@lanips_bp.route('/api/get_lanips', methods=['GET'])
@jwt_required()
def get_lanips():
    client_id = request.args.get('client_id')
    lanip_name = request.args.get('lanip_name')
    lanip_type = request.args.get('lanip_type')
    lanip_ip = request.args.get('lanip_ip')
    page_size = int(request.args.get('page_size'))
    page_current = int(request.args.get('page_current'))
    params = []
    sql = "FROM lanips WHERE 1=1"
    if is_string_valid(client_id):
        sql += " AND client_id = ?"
        params.append(client_id)
    if is_string_valid(lanip_name):
        sql += " AND lanip_name LIKE ?"
        params.append('%' + lanip_name + '%')
    if is_string_valid(lanip_type):
        sql += " AND lanip_type like ?"
        params.append('%' + lanip_type + '%')
    if is_string_valid(lanip_ip):
        sql += " AND lanip_ip like ?"
        params.append('%' + lanip_ip + '%')
    offset = (page_current - 1) * page_size
    rows = fetchall("SELECT * %s ORDER BY lanip_id DESC LIMIT ?, ?" % sql, tuple(params + [offset, page_size]))
    total_count = fetchvalue("SELECT COUNT(*) %s" % sql, tuple(params,))
    return { 'status': 'ok', 'data': rows, 'page_total': total_count }

@lanips_bp.route('/api/add_lanip', methods=['POST'])
@jwt_required()
def add_lanip():
    client_id = request.json.get('client_id')
    lanip_ip = request.json.get('lanip_ip')
    lanip_name = request.json.get('lanip_name')
    lanip_type = request.json.get('lanip_type')
    if is_valid_ip_or_domain(lanip_ip) == False:
        return { 'status': 'error', 'data': 'IP地址格式不正确' }
    row = fetchone("SELECT * FROM lanips WHERE client_id = ? AND lanip_ip = ?", (client_id, lanip_ip))
    if row != None:
        return { 'status': 'error', 'data': 'IP地址已存在' }
    lanip_id = execute("INSERT INTO lanips (client_id, lanip_ip, lanip_name, lanip_type) VALUES (?, ?, ?, ?)", (client_id, lanip_ip, lanip_name, lanip_type))
    return { 'status': 'ok', 'data': lanip_id }

@lanips_bp.route('/api/delete_lanip', methods=['POST'])
@jwt_required()
def delete_lanip():
    lanip_id = request.json.get('lanip_id')
    execute("DELETE FROM lanips WHERE lanip_id = ?", (lanip_id,))
    return { 'status': 'ok', 'data': 'success' }

@lanips_bp.route('/api/update_lanip', methods=['POST'])
@jwt_required()
def update_lanip():
    lanip_id = request.json.get('lanip_id')
    lanip_name = request.json.get('lanip_name')
    lanip_type = request.json.get('lanip_type')
    execute("UPDATE lanips SET lanip_name = ?, lanip_type = ? WHERE lanip_id = ?", (lanip_name, lanip_type, lanip_id))
    return { 'status': 'ok', 'data': 'success' }

@lanips_bp.route('/api/lanip_enable', methods=['POST'])
@jwt_required()
def lanip_enable():
    lanip_id = request.json.get('lanip_id')
    lanip_enable = int(request.json.get('lanip_enable'))
    execute("UPDATE lanips SET lanip_enable = ? WHERE lanip_id = ?", (lanip_enable, lanip_id))
    return { 'status': 'ok', 'data': 'success' }

@lanips_bp.route('/api/add_batch_lanip', methods=['POST'])
@jwt_required()
def batch_add_lanip():
    client_ids = request.json.get('client_ids')
    lanip_name = request.json.get('lanip_name')
    lanip_ip = request.json.get('lanip_ip')
    lanip_type = request.json.get('lanip_type')
    lanip_enable = int(request.json.get('lanip_enable'))
    if is_string_valid(lanip_name) == False:
        return { 'status': 'error', 'data': '名称不能为空' }
    if is_valid_ip_or_domain(lanip_ip) == False:
        return { 'status': 'error', 'data': 'IP地址格式不正确' }
    add_count = 0
    conn, cursor = create_conn()
    try:
        for client_id in client_ids:
            cursor.execute("SELECT * FROM lanips WHERE client_id = ? AND lanip_ip = ?", (client_id, lanip_ip))
            row = cursor.fetchone()
            if row == None:
                cursor.execute("INSERT INTO lanips (client_id, lanip_ip, lanip_name, lanip_type, lanip_enable) VALUES (?, ?, ?, ?, ?)", (client_id, lanip_ip, lanip_name, lanip_type, lanip_enable))
                add_count += 1
        conn.commit()
    except Exception as e:
        print(f"Error: {e}")
        conn.rollback()
    finally:
        cursor.close()
        conn.close()
    return { 'status': 'ok', 'data': add_count }
